package com.knife.news.manage.action;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import com.knife.news.logic.impl.SiteServiceImpl;
import com.knife.news.object.Site;
import com.knife.news.object.Template;
import com.knife.service.HTMLGenerater;
import com.knife.util.CommUtil;
import com.knife.web.Globals;
import com.knife.web.Module;
import com.knife.web.Page;
import com.knife.web.WebForm;

public class StaticManageAction extends ManageAction {
	private HTMLGenerater generater;
	private SiteServiceImpl siteDAO = SiteServiceImpl.getInstance();
	private Site site;
	private String sid;
	
	public Page doInit(WebForm form, Module module) {
		return module.findPage("index");
	}
	
	public Page doSummary(WebForm form, Module module){
		String id=CommUtil.null2String(form.get("id"));
		if("".equals(id)){
			id="1";
		}
		int seo_type=0;
		if(siteDAO.getSiteById(id)!=null){
			site = siteDAO.getSiteById(id);
			form.addResult("site", site);
			seo_type=site.getHtml_rule();
		}
		if(seo_type==0){
			form.addResult("seo", "按标题命名");
		}else{
			form.addResult("seo", "按编号命名");
		}
		return module.findPage("summary");
	}

	public Page doList(WebForm form, Module module) {
		String nowdir = CommUtil.null2String(form.get("id"));
		site=siteDAO.getSite();
		String templateFile = Globals.APP_BASE_DIR + File.separator + "WEB-INF"
				+ File.separator + "templates" + File.separator + "web"
				+ File.separator + site.getTemplate();
		if(nowdir.length()>0){
			templateFile = templateFile + nowdir + File.separator;
			form.addResult("tid", nowdir);
		}
		File templatePath = new File(templateFile);
		List<Template> tList = new ArrayList<Template>();
		if (templatePath.exists()) {
			for (File afile : templatePath.listFiles()) {
				Template aTemplate = new Template(afile);
				tList.add(aTemplate);
			}
		}
		form.addResult("tList", tList);
		return module.findPage("list");
	}
	
	//生成首页
	public Page doGenIndex(WebForm form, Module module) {
		sid = CommUtil.null2String(form.get("sid"));
		generater=new HTMLGenerater(sid);
		if(generater.saveIndexToHtml()){
			form.addResult("msg", "生成成功");
		}else{
			form.addResult("msg", "生成失败");
		}
		return doSummary(form,module);
	}
	
	//生成分类页
	public Page doGenTypes(WebForm form, Module module){
		sid = CommUtil.null2String(form.get("sid"));
		generater=new HTMLGenerater(sid);
		if(generater.saveAllTypesToHtml()){
			form.addResult("msg", "生成成功");
		}else{
			form.addResult("msg", "生成失败");
		}
		return doSummary(form,module);
	}
	
	//生成内容页
	public Page doGenNews(WebForm form, Module module){
		sid = CommUtil.null2String(form.get("sid"));
		generater=new HTMLGenerater(sid);
		if(generater.saveAllNewsToHtml()){
			form.addResult("msg", "生成成功");
		}else{
			form.addResult("msg", "生成失败");
		}
		return doSummary(form,module);
	}
}